/*
 * File Created: 2022-08-03 10:02:12
 * Author: yubaolin (yubaolin6@outlook.com)
 * Desc: 微应用加载状态，及事件监听
 * Last Modified: 2022-08-03 10:02:57
 * Modified By: yubaolin (yubaolin6@outlook.com>)
 */
import { start } from 'qiankun';
import { ref, getCurrentInstance, onMounted,  onBeforeUnmount} from 'vue'
import { statusEventCode, microLifeCycleEvent, dynamicResisterApps } from '@/micro/index'
import { MICRO_MODE, CONTAINER_ID } from './const'

export default function useMicro({appNavList}) {
  const { proxy } = getCurrentInstance()
  const microStatus = ref(null)
  const currentApp = ref(null)

  const microStatusChange = ({eventCode, app}) => {
    if (eventCode == microLifeCycleEvent.afterUnmount) {
      microStatus.value = null
      currentApp.value = null
      return
    }

    microStatus.value = eventCode
    currentApp.value = app
  }

  const microLogicData = computed(() => {
    return {
      main: !currentApp.value || currentApp.value.props.mode == MICRO_MODE.ROUTE,
      contentMicro: currentApp.value && currentApp.value.props.mode == MICRO_MODE.MENU_ROUTE,
      micro: currentApp.value && currentApp.value.props.mode == MICRO_MODE.ROUTE,
      loading: microStatus.value == microLifeCycleEvent.beforeLoad || microStatus.value == microLifeCycleEvent.beforeMount
    }
  })

  onMounted(() => {
    proxy.$eventBus.on(statusEventCode, microStatusChange)

    if(appNavList && appNavList.length > 0){
      let apps = []
      appNavList.forEach(item => {
        if (item.mode) {
          apps.push({
            name: item.code,
            entry: item.url,
            container: '#' + CONTAINER_ID[item.mode],    // 子应用所在容器
            activeRule: [`/#/${item.code}`],   // 子应用触发规则（路径）
            props: {
              appId: item.code, // 可不传，默认name字段
              mode: item.mode, // route：子应用只渲染内容, menu-route：子应用渲染菜单
              routeBase: item.code,
            },
          })
        }
      })
      if (apps.length > 0) {
        dynamicResisterApps(apps)
      }
    }

    start({
      prefetch: 'all',
      sandbox: {
        experimentalStyleIsolation: true
      }
    })
  })

  onBeforeUnmount(() => {
    proxy.$eventBus.off(statusEventCode, microStatusChange)
  })

  return {
    microStatus,
    currentApp,
    microLogicData
  }
}
